function formatUgovorBroj(str){
	var num = str.replace(/[^\d]/g,"");
	var maxlength = 5;
	if(num.length<5){
		var len = maxlength-num.length;
		for(var i=0; i<len; i++){
			num = "0"+num;
		}
	}
	return num;
}
function selectUgovor(obj,komid,komname,objid){
	var obj = document.getElementById(obj);
	if(obj){
		var ugo = prompt("Pretraga ugovora",obj.value);
		if(ugo && ugo.length>2){
			var a = 'duznici.php?a=searchUgo&kword='+escape(ugo)+'&objbroj='+obj.id+'&objid='+objid+'&komid='+komid+'&komname='+komname;
			LoadRSDoc(a,'ypAjaxForm');
		}
	}
}
function updateSelectUgovor(objbroj,objid,komid,komname,ugobroj,ugoid,parid,parnaz){
	var _ugobj = document.getElementById(objbroj);
	var _ugobjid = document.getElementById(objid);
	var _komidobj = document.getElementById(komid);
	var _komnameobj = document.getElementById(komname);
	if(_ugobj && _komidobj && _komnameobj){
		_ugobj.value = ugobroj;
		if(_ugobjid){
			_ugobjid.value = ugoid;
		}
		_komidobj.value = parid;
		_komnameobj.value = parnaz
		//alert(objid+"\n"+komid+"\n"+komname+"\n"+ugoid+"\n"+parid+"\n"+parnaz);
	}else{
		alert("ERROR!\n\n_ugobj: "+_ugobj+"\n_komidobj:"+_komidobj+"\n_komnameobj:"+_komnameobj);
	}
}

function ugovorDetails(ugoid){
	if(ugoid>0){
		LoadRSDoc('duznici.php?a=searchUgo&kword='+ugoid+'&objid=&komid=&komname=','ypAjaxForm');
	}
}
function issueContract(forma){
	var els = forma.elements;
	var br_ugo = els['broj_ugovora'];
	var br_ugo_end = els['broj_ugovora_end'];
	
	var broj_ugovora = br_ugo_end.value?br_ugo.value+"-"+br_ugo_end.value:br_ugo.value;
	
	var kol_pr = els['kol_pracuna'];
	var radnik = els['radnik'];
	var komentar = els['komentar'];
	
	var t1 = testElement2(br_ugo);
	var t2 = testElement2(kol_pr);
	
	if(!t1){
		alert("Broj ugovora nije validan!");
		br_ugo.select();
		return;
	}
	if(!t2){
		alert("Količina predračuna nije validna!");
		kol_pr.select();
		return;
	}
	var action="a=check&br_ugo="+broj_ugovora;
	if(broj_ugovora.match('-')){
		var tmp = broj_ugovora.split("-",2);
		if(tmp[1] <= tmp[0]){
			alert("Drugi broj ugovora je manji ili jednak prvom.")
			return;
		}
	}
	LoadRSDoc("ugovori.php?"+action,"issueContract1('"+broj_ugovora+"','"+kol_pr.value+"','"+radnik.value+"','"+komentar.value+"')");
}
function issueContract1(str,broj_ugovora,kol_pr,radnik,komentar,end_broj){
	var action="a=izdajDB&br_ugo="+broj_ugovora+"&kol_pr="+kol_pr+"&rad_id="+radnik+"&komentar="+komentar;
	var tmp = str.split(";");
	var out="Neki od ugovora su već izdati:\n";
	var ima = false;
	for(var i=0; i<tmp.length; i++){
		var t = tmp[i].split(",",2);
		var bu = t[0];
		var status = (t[1].length>0)?"izdat":"nije izdat";
		if(t[1].length>0){
			out += formatUgovorBroj(bu)+"\n";
			ima=true
		}
	}
	if(ima){
		if(confirm(out+"\n\nDa li da ih storniram i izdam nove?")){
			LoadRSDoc("ugovori.php?"+action,"alert");
		}
	}else{
		LoadRSDoc("ugovori.php?"+action,"alert")
	}
}
function contractEntrance(forma){
	var cont = document.getElementById("container");
	var els = forma.elements;
	var dat_ugo = els["datum"];
	var br_ugo = els["broj_ugovora"];
	var kol_pracuna = els["kol_pracuna"];
	var rad_id = els["radnik"];
	var komitent = els["komitent"];
	var kampanja = els["kampanja"];
	var storno = els["storno"];
	var vracen = els["vracen"];
	var vracenRadnik = els["vracenRadnik"];
	var vracenComment= els["vracenComment"];
	var t1 = testElement2(br_ugo);
	var t2 = testElement2(kol_pracuna);
	
	if(!t1){alert("Broj ugovora nije validan!"); br_ugo.focus; br_ugo.select(); return;}
	if(!t2){alert("Količina predračuna nije validna!"); kol_pracuna.focus(); kol_pracuna.select(); return;}
	
	if(els['komitent'].value.length<1){
		alert("Unesite naziv komitenta!");
		komitent.focus();
		komitent.select();
		return;
	}
	
	if(vracen.checked && vracenRadnik.value<1){
		alert("Odaberite kom radniku ste vratili ugovor.");
		vracenRadnik.focus();
		return;
	}
	
	if(br_ugo.value.length>6){
		if(!confirm("Da li je obnova, aneks ugovora ili nešto treće?")){
			return;
		}
	}
	
	var action="a=ulazDB&br_ugo="+br_ugo.value+"&kol_pr="+kol_pracuna.value+"&rad_id="+rad_id.value;
	action += "&komitent="+escape(komitent.value)+"&kampanja="+kampanja.value;
	
	params=Array();
	params["datum_ugovora"]=dat_ugo.value;
	params["br_ugovora"]=br_ugo.value;
	params["kol_predracuna"]=kol_pracuna.value;
	params["radnik"]=rad_id.value;
	params["komitent"]=komitent.value;
	params["kampanja"]=kampanja.value;
	params["storno"] = storno.checked?1:0;
	params["vracen"] = vracen.checked?vracenRadnik.value:'';
	params["vracenComment"] = escape(vracenComment.value);
	params["artikli"] = Array();
	
	var fsets = forma.getElementsByTagName("fieldset");
	var q="<h3>Molim potvrdite unete podatke:</h3>";
	q+='<table class="contractEntranceConfirm">';
	q+="<tr>";
	q+="<td>dat.ugovora</td>";
	q+="<td>ugovor</td>";
	q+="<td>pr</td>";
	q+="<td>radnik</td>";
	q+="<td>komitent</td>";
	q+="<td>kampanja</td>";
	q+="<td>artikl</td>";
	q+="<td>cena</td>";
	q+="<td>napomena</td>";
	q+="<td>mat</td>";
	q+="<td>storno</td>";
	q+="</tr>";
	for(var i=0; i<fsets.length; i++){
		if(!fsets[i].id.match(/^\d{1,}_/)){
			continue;
		}
		var selects = fsets[i].getElementsByTagName("select");
		var artname = selects[0];
		var arttip = selects[1];
		var artboja = selects[2];
		var artmera = selects[3];
		var inputs = fsets[i].getElementsByTagName("input");
		for(var j=0; j<inputs.length; j++){
			switch(inputs[j].type.toLowerCase()){
				case 'text':
					var artprice = inputs[j].value;
					break;
				case 'checkbox':
					if(inputs[j].name.match(/^non_price_list/)){
						var non_pricelist = inputs[j].checked?true:false;
					}else if(inputs[j].name.match(/^materijal/)){
						var materijal = inputs[j].checked?true:false;
					}else if(inputs[j].name.match(/^potpun_materijal/)){
						var potpun_materijal = inputs[j].checked?true:false;
					}
					break;
			}
		}
		var txtarea = fsets[i].getElementsByTagName("textarea");
		txtarea = txtarea[0];
		var artkomentar = txtarea.value;
		var rad_name = rad_id.options[rad_id.selectedIndex].innerHTML;
		var kampanja_name = kampanja.options[kampanja.selectedIndex].innerHTML;
		q+="<tr>";
		q+="<td align=\"center\">"+dat_ugo.value+"</td>";
		q+="<td>"+br_ugo.value+"</td>";
		q+="<td>"+kol_pracuna.value+"</td>";
		q+="<td>"+rad_name+"</td>";
		q+="<td>"+komitent.value+"</td>";
		q+="<td>"+kampanja_name+"</td>";
		q+="<td><strong>"+artname.options[artname.selectedIndex].innerHTML+"</strong>";
		if(arttip.value>0)
		q+="<br /><span class=\"small\">"+arttip.options[arttip.selectedIndex].innerHTML+"</span>";
		if(artboja.value>0)
		q+="<br /><span class=\"small\">"+artboja.options[artboja.selectedIndex].innerHTML+"</span>";
		if(artmera.value>0)
		q+="<br /><span class=\"small\">"+artmera.options[artmera.selectedIndex].innerHTML+"</span>";
		q+="</td>";
		q+="<td align=\"right\">"+artprice+"</td>";
		non_price_kom = artkomentar?'\ncena je van cenovnika':'cena je van cenovnika';
		artkomentar += (non_pricelist?non_price_kom:'');
		q+="<td>"+artkomentar.replace("\n","<br />")+"</td>";
		q+="<td>"+(materijal?potpun_materijal?'ima':'ima nepotpun':'nema')+"</td>";
		q+= "<td align=\"center\" valign=\"middle\">";
		q+=storno.checked?'<img src="gui/check.gif" />':"&nbsp;";
		q+="</td>";
		q+="</tr>";
		//alert(artname+"\n\n"+"   tip: "+arttip+"\n"+"   boja: "+artboja+"\n"+"   mera: "+artmera+"\n"+"   cena: "+artprice+"\n"+"   van cenovnika: "+non_pricelist+"\n"+"   ima materijal: "+materijal+"\n"+"   Komentar: "+artkomentar);
		var art = Array();
		art["id"] = artname.value;
		art["type"] = (arttip.value>0)?arttip.value:0;
		art["color"] = (artboja.value>0)?artboja.value:0;
		art["unit"] = (artmera.value>0)?artmera.value:0;
		art["price"] = artprice;
		art["mat"] = materijal?1:0;
		art["pot_mat"] = potpun_materijal?1:0;
		art["kom"] = artkomentar;
		params["artikli"].push(art);
	}
	q+="</table>";
	if(params["vracen"]>0){
		q += "<div style=\"float:left;\">Ugovor vraćen radniku: <strong>"+vracenRadnik.options[vracenRadnik.selectedIndex].innerHTML+"</strong></div>";
	}
	ypconfirm(q,"contractEnter",params,null,700);
}
function contractEnter(obj){
	var params = obj.response;
	if(typeof(params) == "object"){
		out = "";
		for(x in params){
			if(typeof(params[x]) == "object"){
				for(var i=0; i<params[x].length; i++){
					out += "{!!}";
					for(y in params[x][i]){
						params[x][i][y] = escape(params[x][i][y])
						out += y+"="+params[x][i][y]+"{!}";
					}
					out = out.substr(0,out.length-3);
				}
				
			}else{
				params[x] = escape(params[x]);
				out += "{!!}"+x+"="+params[x];
			}
		}
		out = out.substr(4);
	}
	var action = "a=ulazDB&params="+out;
	LoadRSDoc("ugovori.php","alert",action,"",1);
	//document.getElementById("container").innerHTML = out;
}
function toggleStorno(obj){
	var hldr = obj.parentNode;
	var fs = obj.parentNode.getElementsByTagName("fieldset");
	var check = obj.checked;
	var w = hldr.offsetWidth;
	var h = hldr.offsetHeight-35;
	if(check){
		var divStorno = document.createElement("div");
		divStorno.id = "stornoMask";
		divStorno.style.width = w + "px";
		divStorno.style.height = h + "px";
		hldr.appendChild(divStorno);
	}else{
		var divs = hldr.getElementsByTagName("div");
		for(x in divs){
			if(divs[x].id == "stornoMask"){
				hldr.removeChild(divs[x]);
				break;
			}
		}
	}
}
function updateGrps(id,obj){
	var val = obj.value;
	LoadRSDoc("classes/fetch.php?a=artikli&type="+val,"fillGrpsSelect('"+id+"')");
}
function fillGrpsSelect(str,dest){
	var tmp = str.split("{!!}");
	var out="<option value=\"0\">---</option>";
	for(var i=0; i<tmp.length; i++){
		var line="";
		var tmp1 = tmp[i].split("{!}");
		var id = tmp1[0];
		var name = tmp1[1];
		var desc = tmp1[2];
		out += '<option value="'+id+'" title="'+desc+'">'+name+'</option>'+"\n";
	}
	document.getElementById(dest).innerHTML = out;
}
function dodajArtikal(obj){
	var parent = obj.parentNode;
	var fieldsets = parent.getElementsByTagName("fieldset");
	var origin = fieldsets[fieldsets.length - 1];
	var clone = origin.cloneNode(true);
	var clone_id = clone.id.split("_");
	var clone_ex = clone_id[1];
	var clone_id = parseInt(clone_id[0]);
	clone.id = (clone_id+1)+"_"+clone_ex;
	
	var tags = Array("label","input","select","textarea");
	var legend = clone.getElementsByTagName("legend");
	legend = legend[0];
	legend = legend.getElementsByTagName("span");
	legend = legend[0];
	var num = parseInt(legend.innerHTML.substr(8));
	legend.innerHTML = "ARTIKAL "+(num+1);
	for(var i=0; i<tags.length; i++){
		var tmp = clone.getElementsByTagName(tags[i]);
		for(var j=0; j<tmp.length; j++){
			switch(tags[i]){
				case "label":
					var old = tmp[j].getAttribute("for");
					tmp[j].setAttribute("for",old+"1");
					break;
				case "input":
					var ime = tmp[j].name;
					if((tmp[j].type != "button") || (ime.match(/^lprice/))){
						tmp[j].name += "1";
						tmp[j].id += "1";
						if(tmp[j].type == "radio"){
							var func = tmp[j].onchange;
							tmp[j].onchange = function(){
								n="";
								for(var i=0; i<parseInt(num);i++){
									n+="1";
								}
								updateGrps("artikl"+n,this);
							}
						}
					}else{
						if(tmp[j].id.match(/^price_btn/)){
							tmp[j].onclick = function(){
								n="";
								for(var i=0; i<parseInt(num);i++){
									n+="1";
								}
								loadPrice('','art_price'+n,this)
							}
						}
					}
					break;
				case "select":
				case "textarea":
					tmp[j].name += "1";
					tmp[j].id += "1";
					break;
			}
		}
	}
	parent.appendChild(clone);
}
function obrisiArtikal(obj){
	var rem = obj.parentNode.parentNode;
	var name = obj.parentNode.getElementsByTagName("span");
	name = name[0].innerHTML;
	var daddy = rem.parentNode;
	var num = daddy.getElementsByTagName("fieldset").length;
	if(num > 1){
		if(confirm("Da li želite da obrišete artikal \""+name+"\"?"))
			daddy.removeChild(rem);
	}else{
		alert("Brisanje nije moguće.\nMora postojati barem jedan artikal.")
	}
}
function loadPrice(str,id,obj){
	if(str.length){
		if(str.match(/^-1/)){
			alert("Za odabrani kriterijum nema podataka u cenovniku.");
			return;
		}
		var obj = document.getElementById(id);
		var tmp = str.split("\n");
		tmp.pop();
		if(tmp.length==1){
			var t = tmp[0].split("{!}");
			obj.value = t[1];
		}else{
			if(document.getElementById("dialog")){
				return;
			}
			var dialog = document.createElement("div");
			dialog.id="dialog"
			dialog.className = "dialog";
			dialog.style.position = "absolute";
			dialog.style.left = Math.round((window.innerWidth-200)/2)+"px";
			dialog.style.top = "100px";
			dialog.style.width = "200px";
			var cont = document.createElement("div");
			cont.className = "dlgContent";
			var p="<form>Odaberite cenu:";
			for(var i=0; i<tmp.length; i++){
				var t = tmp[i].split("{!}");
				artname = t[0];
				cena = t[1];
				tip = t[2];
				boja = t[3];
				un = t[4];
				p += '<input type="radio" name="cena" value="c='+cena+';t='+tip+';b='+boja+';u='+un+'" id="cena'+i+'" ';
				if(i==0)
				p += "checked"
				p += '/>';
				p += '<label for="cena'+i+'">'
				p += "<span style=\"font-weight:bolder\">"+cena+" din.</span>";
				if(tip)
					p += "<br />tip: "+tip
				if(boja)
				p += "<br />boja: "+boja;
				if(un.length)
				p += "<br />mera: "+un;
				p += '</label><br clear="all" />';

			}
			p += '<input type="button" onclick="loadPriceUpdate(this,\''+id+'\')" value="unesi" />';
			p += '<input type="button" onclick="document.body.removeChild(this.parentNode.parentNode.parentNode)" value="poništi" />';
			p+="</form>"
			cont.innerHTML = p;
			var title = document.createElement("div");
			title.innerHTML = (artname.length>22)?artname.substr(0,22)+"...":artname;
			title.className = "title";
			title.onmousedown = function(e){
				this.diffX = e.clientX-parseInt(this.parentNode.style.left);
				this.diffY = e.clientY-parseInt(this.parentNode.style.top);
				this.move=true;
			}
			title.onmouseup = function(){
				this.move=false;
			}
			title.onmousemove = function(e){
				if(this.move){
					this.parentNode.style.left = (e.clientX-this.diffX)+"px";
					this.parentNode.style.top = (e.clientY-this.diffY)+"px";
				}
			}
			title.onmouseout = function(){
				this.move=false;
			}
			document.body.appendChild(dialog);
			dialog.appendChild(title);
			dialog.appendChild(cont);
		}
	}else{
		var datum = document.getElementById("datum");
		if(!datum.value.length){
			alert("Unesite datum ugovora!");
			datum.focus();
			return;
		}
		var fset = obj.parentNode.parentNode;
		var selects = fset.getElementsByTagName("select");
		var art,tip,col;
		out="";
		for(var i=0; i<selects.length; i++){
			var ime = selects[i].name;
			if(ime.match(/^artikl/g)){
				art = (selects[i].value)?(selects[i].value):'';
			}else if(ime.match(/^art_tip/g)){
				tip = (selects[i].value>0)?(selects[i].value):'';
			}else if(ime.match(/^art_boja/g)){
				col = (selects[i].value>0)?(selects[i].value):'';
			}else if(ime.match(/^art_unit/g)){
				un = (selects[i].value>0)?selects[i].value:'';
			}
			//out += selects[i].name+": "+selects[i].value+"\n";
		}
		//LoadRSDoc("classes/fetch.php?a=price&art="+art+"&tip="+tip+"&col="+col+"&un="+un,"loadPrice('"+id+"')");
		LoadRSDoc("classes/fetch.php?a=price&art="+art+"&d="+datum.value,"loadPrice('"+id+"')");
	}
}
function loadPriceUpdate(btn,id){
	var obj=btn.parentNode.elements;
	var input_price = document.getElementById(id);
	var fieldset = input_price.parentNode.parentNode;
	var val=null;
	for(var i=0; i<obj.length; i++){
		if((obj[i].nodeName.toLowerCase()=='input') && (obj[i].checked==true)){
			val=obj[i].value;
			break;
		}
	}
	if(val){
		var tmp = val.split(";");
		var vals = Array();
		for(var i=0; i<tmp.length; i++){
			var t = tmp[i].split("=");
			vals[t[0]]=t[1];
		}
		input_price.value=vals["c"];
		var selects = fieldset.getElementsByTagName("select");
		for(i=0; i<selects.length; i++){
			if(selects[i].name.match(/^art_tip/) && vals["t"]){
				testSelect(selects[i],null,vals["t"]);
			}else if(selects[i].name.match(/^art_boja/) && vals["c"]){
				testSelect(selects[i],"compare",vals["b"]);
			}else if(selects[i].name.match(/^art_unit/) && vals["u"]){
				testSelect(selects[i],null,vals["u"]);
			}
		}
	}
	document.body.removeChild(btn.parentNode.parentNode.parentNode);
}
function testSelect(sel,where,str){
	for(var j=0; j<sel.childNodes.length; j++){
		var opt = (sel.childNodes[j].nodeName.toLowerCase()=="option")?sel.childNodes[j]:null;
		if(!opt)
			continue;
		if(!where){
			var tst = opt.innerHTML;
		}else{
			var tst = opt.getAttribute(where);
		}
		if(tst == str){
			opt.selected=true;
		}else{
			opt.selected=false;
		}
	}
}
function nonPriceList(btn){
	var v=(btn.checked)?false:true;
	var inpts = btn.parentNode.getElementsByTagName("input");
	for(var i=0 ;i<inpts.length; i++){
		var inpt = inpts[i];
		if(inpt.id.match(/^price_btn/)){
			inpt.disabled = !v;
		}else if(inpt.id.match(/^art_price/)){
			inpt.disabled = v;
		}
	}
	var selects = btn.parentNode.parentNode.getElementsByTagName("select");
	for(i=0; i<selects.length; i++){
		if(!selects[i].name.match(/^artikl/)){
			selects[i].disabled = v;
		}
	}
}
function resetTheRest(sel){
	var fset = sel.parentNode;
	var sels = fset.getElementsByTagName("select");
	for(var i=0; i<sels.length; i++){
		if(!sels[i].name.match(/^artikl/)){
			sels[i].selectedIndex = 0;
		}
	}
	var inpts = fset.getElementsByTagName("input");
	for(i=0; i<inpts.length; i++){
		if(inpts[i].type.toLowerCase()=="text" && inpts[i].name.match(/^art_price/g)){
			inpts[i].value = "";
			break;
		}
	}
}
function filterReport(btn,type,page){
	var forma = btn.parentNode.parentNode;
	if(forma.nodeName.toLowerCase() != "form"){
		forma = forma.parentNode;
	}
	
	if(!page) page=1;
	
	var sd = forma.elements['start_date'];
	var ed = forma.elements['end_date'];
	var sud = forma.elements['start_date_ugovor'];
	var eud = forma.elements['end_date_ugovor'];
	var bu = forma.elements['filter_br_ugo'];
	var rad = forma.elements['filter_radnik'];
	var kom = forma.elements['filter_komitent'];
	var mat = forma.elements['filter_materijal'];
	var storno = forma.elements['filter_storno'];
	var potpun = forma.elements['filter_potpun'];
	var tip = forma.elements['filter_tip'];
	var comment = forma.elements['filter_komentar'];
	
	
	var url = 'ugovori.php?a=report&t='+type+'&page='+page;
	if(sd){url += '&start='+sd.value}
	if(ed){url += '&end='+ed.value}
	if(sud){url += '&start_ugo='+sud.value}
	if(eud){url += '&end_ugo='+eud.value}
	if(bu){url += '&bu='+bu.value}
	if(rad){url += '&rad='+rad.value}
	if(kom){url += '&kom='+kom.value}
	if(mat){url += '&mat='+mat.value}
	if(storno){url += '&stor='+storno.value}
	if(potpun){url += '&potpun='+potpun.value}
	if(tip){url += '&tip='+tip.value}
	if(comment){url += '&komentar='+escape(comment.value);}
	LoadRSDoc(url,'setContent')
}
function filterUgovoriRazduzenje(forma){
	var els = forma.elements;
	var action = "";
	for(var i=0; i<els.length; i++){
		if(els[i].name && els[i].value){
			action += "&"+els[i].name+"="+trim(els[i].value);
		}
	}
	LoadRSDoc('ugovori.php?a=report&t=7'+action,'setContent');
}
function clearFilter(obj,id){
	var forma = obj.parentNode.parentNode;
	if(forma.nodeName.toLowerCase() != "form"){
		forma = forma.parentNode;
	}
	var inputs = forma.getElementsByTagName("input");
	var btn;
	for(var i=0; i<inputs.length; i++){
		if(inputs[i].type.toLowerCase()=='text'){
			inputs[i].value='';
		}
		if(inputs[i].id == id){
			btn=inputs[i];
		}
	}
	btn.click();
}
function reportRadnik(forma){
	var id = forma.radnik_id.value;
	var tip = forma.report_tip.value;
	var o = forma.report_radnik_od.value;
	var d = forma.report_radnik_do.value;
	var ime = forma.rime.value;
	var prez = forma.rprez.value;
	
	var params = "id="+id+"&tip="+tip+"&od="+o+"&do="+d+"&ime="+ime+"&prez="+prez;
	LoadRSDoc("ugovori.php?a=report&t=4&"+params,"setContent");
}
function deleteUlazUgovora(id,obj,e){
	if(id){
		var popup = document.getElementById("deleteItem");
		if(popup){
			popup.parentNode.removeChild(popup);
		}
		popup = document.createElement("a");
		popup.href = "javascript:void(0);"
		popup.id_ulaza = id;
		popup.onmouseover = function(e){
			e.stopPropagation();
			this.style.display="block";
		}
		popup.onclick = function(){
			LoadRSDoc('ugovori.php?a=delitem&t='+this.id_ulaza,'setContent');
		}
		popup.id = "deleteItem";
		popup.innerHTML = "obriši";
		obj.appendChild(popup);
		var t = e.pageY;
		popup.style.top = t+"px";
		popup.style.marginLeft = "30px";
		//window.status = e.pageX+"-"+e.pageY;
		popup.onmouseover = function(){
			this.style.display="block";
		}
		obj.onclick = function(){
			deleteUlazUgovora(0,null,null);
		}
	}else{
		var popup = document.getElementById("deleteItem");
		if(popup)
			popup.parentNode.removeChild(popup);
	}
}
function contractMatSearch(forma){
	var cont = document.getElementById("ulaz_mat_content");
	var br_ugo = forma.broj_ugovora;
	var kom = forma.komitent;
	if(br_ugo.value || kom.value){
		LoadRSDoc("ugovori.php?a=ulaz_mat_search&ugo="+br_ugo.value+"&kom="+kom.value,"ypAjaxForm");
	}
}
function contractMatEdit(content){
	var mat_content = document.getElementById("ulaz_mat_content");
	mat_content.innerHTML = content;
}
function contractMatSave(forma){
	var ul_id = forma.ulaz_id.value;
	var p = (forma.potpun.checked)?1:0;
	var napomena = forma.napomena.value;
	
	var type=false;
	for(var i=0; i<forma.um_type.length; i++){
		var it = forma.um_type[i];
		if(it.checked){
			type = it.value;
			break;
		}
	}
	
	if(type !== false){
		var action = "a=ulaz_mat_save&id="+ul_id+"&t="+type+"&p="+p+"&n="+escape(napomena);
		//alert(action)
		LoadRSDoc("ugovori.php","alert",action,"",1);
	}else{
		alert("Niste odabrali tip ulaza materijala!")
	}
}

function afterReportUI(response){
	ypAjaxForm(response);
}

function selectUgovorRazduzivanje(btn){
	var brugo_obj = btn.previousSibling.previousSibling;
	var brugo = prompt("Broj ugovora",brugo_obj.innerHTML);
	brugo = trim(brugo);
	
	if(brugo.length && brugo!=trim(brugo_obj.innerHTML)){
		LoadRSDoc("ugovori.php?a=razduzi&mod=searchIzd&brugo="+brugo,"ypAjaxForm");
	}
}
function setIzdatUgovor(id,brugo,datum, radnik){
	document.getElementById("izd_brugo").innerHTML = brugo;
	document.getElementById("datum_ugo").innerHTML = datum;
	document.getElementById("radnik_ugo").innerHTML = radnik;
	document.getElementById("izd_id").value = id;
}
function razduziUgovor(forma){
	var els = forma.elements;
	if(els["izd_id"].value<1){
		alert("Prvo odaberite ugovor!");
		document.getElementById("selectUgovor").focus();
		return;
	}
	if(els["radnik"].value<1){
		alert("Odaberite radnika.");
		document.getElementById("radnik").focus();
		return;
	}
	
	var action = "a=razduzi&mod=razduzi";
	action += "&izd_id="+els["izd_id"].value;
	action += "&radnik="+els["radnik"].value;
	
	LoadRSDoc("ugovori.php?"+action,"alert");
}
function vratiUgovor(forma){
	var els = forma.elements;
	var ulaz_id	= els['ulaz_id'].value;
	var radnik	= els['radnik'].value;
	var komentar= escape(els["komentar"].value);
	
	var action = "ugovori.php?a=vracanje&mod=vrati";
	action += "&ulaz_id="+ulaz_id;
	action += "&radnik="+radnik;
	action += "&komentar="+komentar;
	
	LoadRSDoc(action,"afterVratiUgovor");
}
function afterVratiUgovor(response){
	closeYpAjaxForm();
	alert(response);
	LoadRSDoc('ugovori.php?a=report&t=2','setContent');
}
function toggleUgovorTab(btn){
	var bq = btn.parentNode.nextSibling.nextSibling;
	bq.style.display = bq.style.display=="none"?"block":"none";
}

function resetUgovorLid(){
	var lid  = document.getElementById("ugovor_lid");
	var grad = document.getElementById("ugovor_grad");
	var lops = document.getElementById("ugovor_lokops");
	var nase = document.getElementById("ugovor_naselje");
	
	lid.value="";
	grad.selectedIndex = 0;
	lops.selectedIndex = 0;
	nase.selectedIndex = 0;
}
function ugovorProblemOnchange(sel){
	//alert(sel.value);
}
function updateStavkeRow(obj){
	var tr = obj.parentNode.parentNode;
	var td = tr.getElementsByTagName("td");
	
	var porezSEL = document.getElementById("ugovor_porez");
	var porezPERC = parseFloat(porezSEL.options[porezSEL.selectedIndex].getAttribute("perc"));
	
	var art = td[1].getElementsByTagName("select")[0];
	var kol = td[2].getElementsByTagName("input")[0];
	var cena = td[3].getElementsByTagName("input")[0];
	var popust = td[4].getElementsByTagName("input")[0];
	var porez = td[5].getElementsByTagName("input")[0];
	var ukupno = td[6].getElementsByTagName("input")[0];
	
	/*var jm = obj.previousSibling.previousSibling;
	var me = jm.previousSibling.previousSibling;
	var bo = me.previousSibling.previousSibling;
	var ti = bo.previousSibling.previousSibling;
	
	jm.value = obj.options[obj.selectedIndex].getAttribute("jmere");
	me.value = obj.options[obj.selectedIndex].getAttribute("mera");
	bo.value = obj.options[obj.selectedIndex].getAttribute("boja");
	ti.value = obj.options[obj.selectedIndex].getAttribute("tip");*/
	
	//alert(art.value+"\n"+ti.value+"\n"+bo.value+"\n"+me.value+"\n"+jm.value);
	
	if(art.value>0){
		var cenaVJ = parseFloat(art.options[art.selectedIndex].getAttribute("cena"));
		var cenaV = cenaVJ*parseInt(kol.value);
		var popv;
		if(popust.value.match(/%/)){
			var popv = parseFloat(popust.value.replace(/[^\d]/g,""));
			popv = parseFloat(cenaV*popv/100);
		}else{
			popv = parseFloat(strip_number_format(popust.value));
		}
		popust.value = number_format(popv,2);
		
		cena.value = number_format(cenaVJ,2);
		var porezV = kol.value>0?(cenaV-popv)*porezPERC/100:0;
		porez.value = number_format(porezV,2);
		
		ukupno.value = kol.value>0?number_format(cenaV-popv+porezV,2):"0,00";
	}else{
		cena.value = porez.value = ukupno.value = "0,00";
	}
	updateCenaUkupno(tr.parentNode);
}
function updateCenaUkupno(table){
	var tr = table.getElementsByTagName("tr");
	
	var _bru = document.getElementById("ugovor_iznos_bruto");
	var _kor = document.getElementById("ugovor_iznos_korekcija");
	var _por = document.getElementById("ugovor_iznos_porez");
	var _nto = document.getElementById("ugovor_iznos_neto");
	
	var bru=0;
	var kor=0;
	var pr=0;
	var nto=0;
	for(var i=1; i<tr.length; i++){
		var td = tr[i].getElementsByTagName("td");
		var kol	= strip_number_format(td[2].getElementsByTagName("input")[0].value); kol=kol.length>0?kol:0;
		var cen	= strip_number_format(td[3].getElementsByTagName("input")[0].value); cen=cen.length>0?cen:0;
		var pp	= strip_number_format(td[4].getElementsByTagName("input")[0].value); pp=pp.length>0?pp:0;
		var por	= strip_number_format(td[5].getElementsByTagName("input")[0].value); por=por.length>0?por:0;
		var uk	= strip_number_format(td[6].getElementsByTagName("input")[0].value); uk=uk.length>0?uk:0;
		
		nto += parseFloat(kol*cen);
		kor += parseFloat(pp);
		pr  += parseFloat(por);
		bru += parseFloat(uk);
	}
	
	_bru.value = number_format(bru,2);
	_kor.value = number_format(kor,2);
	_por.value = number_format(pr,2);
	_nto.value = number_format(nto,2);
}
function updateUgovorCenovnikStavke(response){
	var tmp = response.split(/\{!\}/);
	var date = tmp[0];
	var cenovnik_id=tmp[1];
	response = tmp[2];
	var cenovnik = document.getElementById("ugovor_cenovnik");
	var stavke = document.getElementById("stavkeTable");
	
	//ypAjaxForm('<textarea>'+response+'<texarea>');
	if(cenovnik_id>0){
		cenovnik.innerHTML = date;
		cenovnik.setAttribute("cenovnik_id",cenovnik_id);
		var trs = stavke.getElementsByTagName("tr");
		for(var i=1; i<trs.length; i++){
			var sel = trs[i].getElementsByTagName("select")[0];
			if(sel){
				sel.innerHTML = response;
			}
		}
		//stavke.innerHTML = response;
		updateCenaUkupno(document.getElementById("stavkeTable"));
	}else{
		cenovnik.innerHTML = date;
		//alert("Ne postoji cenovnik za zadati datum");
		alert(response);
	}
}
function ugovorOnChangeStavkaArt(sel){
	var paket=parseInt(sel.options[sel.selectedIndex].getAttribute('paket'));
	sel.previousSibling.previousSibling.value=paket;
	
	updateStavkeRow(sel);
	updateStavkeTok(sel);
}
function updateStavkeTok(sel){
	var id=sel.parentNode.parentNode.id;
	var artName = sel.options[sel.selectedIndex].innerHTML;
	var paket = parseInt(sel.options[sel.selectedIndex].getAttribute("paket"));
	
	// ako nije paket
	if(paket<1){
		var li = document.getElementById("item_data_"+id);
		if(li.getAttribute("paket")>0){
			xLi = li.childNodes[0].childNodes[0];
			li.innerHTML = xLi.innerHTML;
			li.setAttribute("paket","0");
		}
		
		var tagNames = Array("input", "select", "textarea", "label");
		for(j=0; j<tagNames.length; j++){
			var _els = li.getElementsByTagName(tagNames[j]);
			var setID = id;
			var setI = i;
			for(var k=0; k<_els.length; k++){
				if(tagNames[j] == "label"){
					var f = _els[k].getAttribute("for");
					if(f){
						var tmp = f.split(/(_\d+)/);
						var base = f.substr(0,f.lastIndexOf("_"));
						if(tmp.length>=5){
							if(_els[k].parentNode.parentNode.className=="materijalList"){
								if(tmp.length>=7){
									base = base.substr(0,base.lastIndexOf("_"));
								}
							}else if(_els[k].parentNode.parentNode.className=="internet_data_periodi"){
								if(tmp.length>=7){
									base = base.substr(0,base.lastIndexOf("_"));
								}
							}else{
								base = base.substr(0,base.lastIndexOf("_"));
							}
						}
						_els[k].setAttribute("for",base+"_"+id);
					}
				}else{
					var n = _els[k].name;
					if(n){
						var tmp = n.split(/(_\d+)/);
						var base = n.substr(0,n.lastIndexOf("_"));
						if(tmp.length>=5){
							if(_els[k].parentNode.parentNode.className=="materijalList"){
								if(tmp.length>=7){
									base = base.substr(0,base.lastIndexOf("_"));
								}
							}else if(_els[k].parentNode.parentNode.className=="internet_data_periodi"){
								if(tmp.length>=7){
									base = base.substr(0,base.lastIndexOf("_"));
								}
							}else{
								base = base.substr(0,base.lastIndexOf("_"));
							}
						}
						_els[k].name = base+"_"+id;
						_els[k].id = _els[k].name;
					}
				}
			}
		}
		
		var h3 = li.getElementsByTagName("h3")[0];
		h3.innerHTML = artName;
		h3.setAttribute("artid",sel.value);
		
	// ako je paket
	}else{
		var artSadrzaj = sel.options[sel.selectedIndex].getAttribute("sadrzaj");
		var artSadrzajDesc = sel.options[sel.selectedIndex].getAttribute("sadrzaj_desc");
		
		var artikli=artSadrzaj.split("\n");
		var artikliDesc=artSadrzajDesc.split("\n");
		for(var i=0; i<artikli.length; i++){
			var artItems = artikli[i].split(";");
			var artDescItems = artikliDesc[i].split(";");
			var li = document.getElementById("item_data_"+id+"_"+i);
			if(li){
				li.parentNode.parentNode.innerHTML = li.innerHTML;
			}
			
			var par = document.getElementById("item_data_"+id);
			var html;
			if(i == 0){
				html = par.innerHTML;
				par.setAttribute("paket","1");
				par.innerHTML = "<ul></ul>";
			}else{
				html = par.childNodes[0].childNodes[0].innerHTML;
			}
			par = par.childNodes[0];
			var li = document.createElement("li");
			li.id = "item_data_"+id+"_"+i;
			li.innerHTML = html;
			
			var tagNames = Array("input", "select", "textarea", "label");
			for(j=0; j<tagNames.length; j++){
				var _els = li.getElementsByTagName(tagNames[j]);
				
				for(var k=0; k<_els.length; k++){
					var setID = id;
					var setI = i;
					if(tagNames[j] == "label"){
						var f = _els[k].getAttribute("for");
						if(f){
							var tmp = f.split(/(_\d+)/);
							tmp = removeEmptyItems(tmp);
							var base = f.substr(0,f.lastIndexOf("_"));
							
							// ako je niz "single" varijabli ili nizova
							if(tmp.length>2){
								
								if(_els[k].parentNode.parentNode.className=="materijalList"){
									// ako je niz nizova
									if(tmp.length>3){
										base = base.substr(0,base.lastIndexOf("_"));
									}
								}else if(_els[k].parentNode.parentNode.className=="internet_data_periodi"){
									var tmp1 = f.split(/(_\d+)/);
									setI = f.substr(f.lastIndexOf("_")+1);
									setID=i;
									
									// ako je niz nizova
									if(tmp.length>3){
										base = base.substr(0,base.lastIndexOf("_"));
									}
								}else{
									base = base.substr(0,base.lastIndexOf("_"));
								}
							}
							_els[k].setAttribute("for",base+"_"+setID+"_"+setI);
						}
					}else{
						var n = _els[k].name;
						if(n){
							var tmp = n.split(/(_\d+)/);
							tmp = removeEmptyItems(tmp);
							
							var base = n.substr(0,n.lastIndexOf("_"));
							
							// ako je niz "single" varijabli ili nizova
							if(tmp.length>2){
								if(_els[k].parentNode.parentNode && _els[k].parentNode.parentNode.className=="materijalList"){
									// ako je niz nizova
									if(tmp.length>3){
										base = base.substr(0,base.lastIndexOf("_"));
									}
								}else if(_els[k].parentNode.parentNode && _els[k].parentNode.parentNode.className=="internet_data_periodi"){
									var tmp1 = n.split(/(_\d+)/);
									setI = n.substr(n.lastIndexOf("_")+1);
									setID=i;
									// ako je niz nizova
									if(tmp.length>3){
										base = base.substr(0,base.lastIndexOf("_"));
									}
								}else{
									base = base.substr(0,base.lastIndexOf("_"));
								}
							}
							_els[k].name = base+"_"+setID+"_"+setI;
							_els[k].id = _els[k].name;
						}
					}
				}
			}
			
			var h3 = li.getElementsByTagName("h3")[0];
			h3.innerHTML = artDescItems[0];
			h3.setAttribute("artid",artItems[0]);
			
			li.style.display="block";
			par.appendChild(li);
			par.style.display="block";
		}
	}
	
}
function toggleStavkaTokData(btn){
	var id = btn.parentNode.parentNode.id;
	var hldr = document.getElementById("item_data_"+id);
	if(hldr.style.display=='block'){
		hldr.style.display="none";
		//btn.style.backgroundImage = "url(gui/ugovori/tok.gif)";
		btn.className = "tok";
	}else{
		hldr.style.display="block";
		btn.className = "tok tokHover";
		//btn.style.backgroundImage = "url(gui/ugovori/tok_hover.gif)";
	}
}
function stavkaAddRow(btn){
	var table = btn.parentNode.parentNode.parentNode;
	var tr = table.getElementsByTagName("tr");
	
	if(tr.length>1){
		var lastRow = tr[tr.length-1];
		var newID = parseInt(lastRow.id)+1;
		
		var ntr = lastRow.cloneNode(true);
		ntr.id = newID;
		var inpts = ntr.getElementsByTagName("input");
		for(var i=0; i<inpts.length; i++){
			var li = inpts[i].id.lastIndexOf("_");
			inpts[i].id = inpts[i].id.substr(0,li)+"_"+newID;
			inpts[i].name = inpts[i].id;
		}
		var sels = ntr.getElementsByTagName("select");
		for(i=0; i<sels.length; i++){
			var ls = sels[i].id.lastIndexOf("_");
			sels[i].id = sels[i].id.substr(0,ls)+"_"+newID;
			sels[i].name = sels[i].id;
		}
		table.appendChild(ntr);
		var liTOK = document.getElementById("item_data_"+lastRow.id);
		var paket = parseInt(liTOK.getAttribute("paket"));
		if(paket==1){
			var nli = liTOK.childNodes[0].childNodes[0].cloneNode("true");
			var newID = parseInt(lastRow.id)+1;
			nli.id = "item_data_"+newID;
			
			var tagNames = Array("input","select","textarea","label");
			for(var i=0; i<tagNames.length; i++){
				var _els = nli.getElementsByTagName(tagNames[i]);
				for(var j=0; j<_els.length; j++){
					if(_els[j].nodeName=="label"){
						var f = _els[j].getAttribute("for");
						alert(f);
						if(f){
							var base = f.substr(0,f.lastIndexOf("_"));
							base=base.substr(0,base.lastIndexOf("_"));
							_els[j].setAttribute("for",base+"_"+newID);
						}
					}else{
						if(_els[j].name){
							var base=_els[j].name.substr(0,_els[j].name.lastIndexOf("_"));
							base=base.substr(0,base.lastIndexOf("_"));
							_els[j].name = base+"_"+newID;
							_els[j].id = _els[j].name
						}
					}
				}
			}
			
			
			liTOK.parentNode.appendChild(nli);
			
		}else{
			var nli = duplicateObject1(liTOK,liTOK.parentNode);
		}
		
		updateCenaUkupno(table);
		
		
	}
}
function stavkaDeleteRow(btn){
	var table = btn.parentNode.parentNode.parentNode;
	var tr = table.getElementsByTagName("tr");
	if(tr.length>2){
		if(confirm("Da li ste sigurni u vezi brisanja?")){
			for(var i=(tr.length-1); i>0; i--){
				var l = table.getElementsByTagName("tr");
				if(tr[i].className=="selected" && l.length>2){
					var li = document.getElementById("item_data_"+tr[i].id);
					li.parentNode.removeChild(li);
					table.removeChild(tr[i]);
					i--;
				}
			}
			updateCenaUkupno(table);
		}
	}
	
}
function importKomitentFromBasicData(btn){
	var komname=btn.nextSibling.nextSibling;
	var komid=komname.nextSibling.nextSibling;
	
	var bkomname = document.getElementById("ugovor_komitent_name");
	var bkomid = document.getElementById("ugovor_komitent_id");
	
	komname.value = bkomname.value;
	komid.value = bkomid.value;
}

/****************************************\
|**********	 DEKLARACIJE	*************|
\****************************************/
function deklaracijaAdd(btn){
	var offset=25;
	
	var nli = document.getElementById("deklaracija_template_li").cloneNode(true);
	
	var ol = btn.nextSibling.nextSibling;
	var olli = ol.getElementsByTagName("li");
	var lastID = olli[olli.length-1].id;
	var index = parseInt(lastID.substr(lastID.lastIndexOf("_")+1));
	index = index>0?index+1:1;
	nli.id = "deklaracija_li_"+index;
	nli.setAttribute("index",index);
	ol.appendChild(nli);
	
	var divC = document.getElementById('deklaracija_template_div');
	var divH = document.getElementById('deklaracije_holder_ul');
	var maxZ = divH.getAttribute("maxZ"); maxZ=maxZ>1?parseInt(maxZ):1;
	var ndiv = divC.cloneNode(true);
	ndiv.id="deklaracija_div_"+index;
	ndiv.style.zIndex = maxZ+1;
	//ndiv.style.marginTop = ((index-1)*offset)+"px";
	//ndiv.style.marginLeft = ndiv.style.marginTop;
	
	var inpt = ndiv.getElementsByTagName("input");
	var txts = ndiv.getElementsByTagName("textarea");
	var sels = ndiv.getElementsByTagName("select");
	var lbls = ndiv.getElementsByTagName("label");
	
	// input
	for(var i=0; i<inpt.length; i++){
		if(inpt[i].name){
			inpt[i].name = inpt[i].name+"_"+index;
			inpt[i].id = inpt[i].name;
		}
	}
	// textarea
	for(var i=0; i<txts.length; i++){
		if(txts[i].name){
			txts[i].name = txts[i].name+"_"+index;
			txts[i].id = txts[i].name;
		}
	}
	// select
	for(var i=0; i<sels.length; i++){
		if(sels[i].name){
			sels[i].name = sels[i].name+"_"+index;
			sels[i].id = sels[i].name;
		}
	}
	// label
	for(var i=0; i<lbls.length; i++){
		var f = lbls[i].getAttribute("for");
		if(f.length){
			lbls[i].setAttribute("for",f+"_"+index);
		}
	}
	
	divH.appendChild(ndiv);
	divH.setAttribute("maxZ",maxZ+1);
}
function deklaracijaOnTop(btn){
	var z=parseInt(btn.parentNode.getAttribute('maxZ'));
	z=(z>0)?z:1;
	var nz=(parseInt(btn.style.zIndex)<z)?z+1:z;
	window.status = btn.parentNode.id+": "+z+" => "+nz;
	btn.style.zIndex=nz;
	btn.parentNode.setAttribute('maxZ',nz);
}
function removeDeklaracija(li){
	var index = li.getAttribute("index");
	if(confirm("Potvrdite brisanje deklaracije #"+index)){
		var dekl = document.getElementById("deklaracija_div_"+index);
		dekl.parentNode.removeChild(dekl);
		li.parentNode.removeChild(li);
	}
}
function toggleDeklaracije(btn){
	var offset = 25;
	var start = 50;
	var indx = parseInt(btn.parentNode.getAttribute('index'));
	 var _obj=document.getElementById('deklaracija_div_'+indx);
	 _obj.style.display=(_obj.style.display=='block')?'none':'block';
	 _obj.style.left=(start+(indx*offset))+'px';
	 _obj.style.top=_obj.style.left;
	 _obj.pressed=false;
}
function deklaracijaImportKomitentData(b,type){
	var komid = document.getElementById("ugovor_komitent_id");
	var li = b.parentNode.parentNode;
	if(komid.value>0){
		LoadRSDoc("ugovori.php?a=deklaracija&mod=importKomitentData&id="+komid.value,"updateDeklaracijaKomitent('"+type+"','"+li.id+"')");
	}else{
		alert("Prvo odaberite komitenta!");
		var btn = komid.nextSibling.nextSibling.nextSibling.nextSibling;
		li.style.display='none';
		btn.focus();
	}
}
function updateDeklaracijaKomitent(response,type,lid){
	if(typeof(type)=="undefined"){
		type=1;
	}
	type=parseInt(type);
	var li=document.getElementById(lid);
	switch(type){
		default:
		case 1:
			ids = Array("dekl_name","dekl_adresa","dekl_matbr","dekl_odg_ime","dekl_odg_jmbg");
			break;
		case 2:
			ids = Array("dekl_creator_name","dekl_creator_adresa","dekl_creator_matbr","dekl_creator_odg_ime","dekl_creator_odg_jmbg");
			break;
	}
	
	var data = Array();
	var tmp = response.split(/\n/);
	for(var i=0; i<tmp.length; i++){
		if(tmp[i].match(/=/)){
			var tmp1 = tmp[i].split(/=/);
			data[tmp1[0]]=tmp1[1];
		}
	}
	
	var inpts = li.getElementsByTagName("input"); 
	for(var i=0; i<inpts.length; i++){
		var n = inpts[i].name;
		
		var rgx0 = new RegExp("^"+ids[0]);
		var rgx1 = new RegExp("^"+ids[1]);
		var rgx2 = new RegExp("^"+ids[2]);
		var rgx3 = new RegExp("^"+ids[3]);
		var rgx4 = new RegExp("^"+ids[4]);
		
		if(n.match(rgx0)){
			inpts[i].value = data["komitent_name"];
		}else if(n.match(rgx1)){
			inpts[i].value = data["komitent_adresa"];
		}else if(n.match(rgx2)){
			inpts[i].value = data["komitent_matbr"];
		}else if(n.match(rgx3)){
			inpts[i].value = data["komitent_vlasnik_name"];
		}else if(n.match(rgx4)){
			inpts[i].value = data["komitent_vlasnik_jmbg"];
		}
	}
}

/****************************************\
|********		DOPISI		*************|
\****************************************/
function dopisAdd(btn){
	var offset=25;
	
	var nli = document.getElementById("dopis_template_li").cloneNode(true);
	
	var ol = btn.nextSibling.nextSibling;
	var olli = ol.getElementsByTagName("li");
	var lastID = olli[olli.length-1].id;
	var index = parseInt(lastID.substr(lastID.lastIndexOf("_")+1));
	index = index>0?index+1:1;
	nli.id = "dopis_li_"+index;
	nli.setAttribute("index",index);
	ol.appendChild(nli);
	
	var divC = document.getElementById('dopis_template_div');
	var divH = document.getElementById('dopisi_holder_ul');
	var maxZ = divH.getAttribute("maxZ"); maxZ=maxZ>1?parseInt(maxZ):1;
	var ndiv = divC.cloneNode(true);
	ndiv.id="dopis_div_"+index;
	ndiv.style.zIndex = maxZ+1;
	//ndiv.style.marginTop = ((index-1)*offset)+"px";
	//ndiv.style.marginLeft = ndiv.style.marginTop;
	
	var inpt = ndiv.getElementsByTagName("input");
	var txts = ndiv.getElementsByTagName("textarea");
	var sels = ndiv.getElementsByTagName("select");
	var lbls = ndiv.getElementsByTagName("label");
	
	// input
	for(var i=0; i<inpt.length; i++){
		if(inpt[i].name){
			inpt[i].name = inpt[i].name+"_"+index;
			inpt[i].id = inpt[i].name;
		}
	}
	// textarea
	for(var i=0; i<txts.length; i++){
		if(txts[i].name){
			txts[i].name = txts[i].name+"_"+index;
			txts[i].id = txts[i].name;
		}
	}
	// select
	for(var i=0; i<sels.length; i++){
		if(sels[i].name){
			sels[i].name = sels[i].name+"_"+index;
			sels[i].id = sels[i].name;
		}
	}
	// label
	for(var i=0; i<lbls.length; i++){
		var f = lbls[i].getAttribute("for");
		if(f.length){
			lbls[i].setAttribute("for",f+"_"+index);
		}
	}
	
	divH.appendChild(ndiv);
	divH.setAttribute("maxZ",maxZ+1);
}
function removeDopis(li){
	var index = li.getAttribute("index");
	if(confirm("Potvrdite brisanje dopisa #"+index)){
		var dekl = document.getElementById("dopis_div_"+index);
		dekl.parentNode.removeChild(dekl);
		li.parentNode.removeChild(li);
	}
}
function toggleDopisi(btn){
	var offset = 25;
	var start = 50;
	var indx = parseInt(btn.parentNode.getAttribute('index'));
	var _obj=document.getElementById('dopis_div_'+indx);
	_obj.style.display=(_obj.style.display=='block')?'none':'block';
	_obj.style.left=(start+(indx*offset))+'px';
	_obj.style.top=_obj.style.left;
	_obj.pressed=false;
}

/*****************************************\
|**************	MATERIJAL	**************|
\*****************************************/
function ugovorAddMaterijal(btn){
	var ul = btn.parentNode.nextSibling.nextSibling.nextSibling;
	var date = document.getElementById("ugovor_datum").value;
	var action = "a=materijal&mod=new&date="+date;
	document.body._ugovorAddMatList=ul;
	LoadRSDoc("ugovori.php","ypAjaxForm",action,"text",1);
}
function ugovorEditMaterijal(btn){
	var li = btn.parentNode;
	var inpts = btn.parentNode.getElementsByTagName("input");
	var inpt = inpts[0];
	var action = "a=materijal&mod=edit&data="+inpt.value;
	document.body._ugovorAddMatList=li;
	LoadRSDoc("ugovori.php","ypAjaxForm",action,"text",1);
}
function afterUgovorAddMaterijal(forma,edit){
	var destObj = document.body._ugovorAddMatList;
	var els = forma.elements;
	
	edit = edit>0?true:false;
	
	els["_date"].value = trim(els["_date"].value);
	if(els["_date"].value.length == 0 || !els["_date"].value.match(/^\d{1,2}\.\d{1,2}\.\d{2,4}$/)){
		alert("Morate uneti datum ulaza materijala u formatu: dd.mm.gggg\n\td=dan\n\tm=mesec\n\tg=godina"); return;
	}
	
	
	var mat = Array();
	for(x in els){
		var t = typeof(els[x]);
		if(t.toLowerCase() == "object"){
			if(els[x].name.match(/^_tm_/)){
				if(els[x].checked){
					mat.push(els[x].value+"{!}"+els[x].getAttribute("naziv"));
				}
			}
		}
	}
	var len = destObj.getElementsByTagName("li");
	var newID = parseInt(len.length)+1;
	var li = document.createElement("li");
	var matdata = "id={!!}";
	matdata += "date="+trim(els["_date"].value)+"{!!}";
	matdata += "tip_ulaza="+els["_tip_ulaza"].value+"{!!}";
	matdata += "upotrebljiv="+(els["_upotrebljiv"].checked?'1':'0')+"{!!}";
	
	var nap = trim(els["_napomena"].value);
	matdata += "napomena="+escape(nap)+"{!!}";
	matdata += "tip_materijala="
	var htmlVrste="";
	if(mat.length){
		for(var i=0; i<mat.length; i++){
			matdata += mat[i].substr(0,mat[i].indexOf("{!}")+3)
			htmlVrste += mat[i].substr(mat[i].indexOf("{!}")+3)+", ";
		}
		//matdata = matdata.substr(0,matdata.length-3);
		htmlVrste = htmlVrste.substr(0,htmlVrste.length-2);
	}
	var html = '<input type="hidden" name="mat_data_'+newID+'" value="'+matdata+'" />';
	html += '<input type="button" onclick="removeFromParent(this.parentNode)" class="delete" />';
	html += '<input type="button" title="izmeni" onclick="ugovorEditMaterijal(this)" class="edit" />';
	html += '<span class="mat_date">'+trim(els["_date"].value)+'</span>';
	html += '<span class="mat_upotrebljiv" upotrebljiv="'+((els["_upotrebljiv"].checked)?'yes':'no')+'">&nbsp;</span>';
	html += '<span class="mat_vrste">'+htmlVrste+'</span>';
	html += '<span class="mat_tip_ulaza">'+els["_tip_ulaza"].options[els["_tip_ulaza"].selectedIndex].innerHTML+'</span>';
	if(trim(els["_napomena"].value).length>0){
		html += '<span class="mat_napomena">';
		html += '<img src="gui/icons/napomena.gif" align="left" />';
		html += '<pre>'+trim(els["_napomena"].value)+'</pre></span>';
	}
	html += '<br clear="all" />';
	li.innerHTML = html;
	if(edit){
		destObj.innerHTML = html;
	}else{
		destObj.insertBefore(li,destObj.childNodes[0]);//appendChild(li);
	}
	closeYpAjaxForm();
}
function ugovorAddAction(btn){
	var ul = btn.parentNode.nextSibling.nextSibling.nextSibling.nextSibling;
	var action = "a=tokActions&mod=new"
	document.body._ugovorAddActList=ul;
	LoadRSDoc("ugovori.php","ypAjaxForm",action,"text",1);
}
function ugovorEditAction(btn){
	var li = btn.parentNode;
	var inpts = btn.parentNode.getElementsByTagName("input");
	var inpt = inpts[0];
	var action = "a=tokActions&mod=edit&data="+inpt.value;
	document.body._ugovorAddActList=li;
	LoadRSDoc("ugovori.php","ypAjaxForm",action,"text",1);
}
function afterUgovorAddAction(forma,edit){
	var els = forma.elements;
	var destObj = document.body._ugovorAddActList;
	
	edit = edit>0?true:false;
	
	var newID = (destObj.getElementsByTagName("li").length) + 1;
	
	var urednik_id=els["_editor"].value;
	var urednik_name=els["_editor"].options[els["_editor"].selectedIndex].innerHTML;
	var dizajner_id=els["_designer"].value;
	var dizajner_name=els["_designer"].options[els["_designer"].selectedIndex].innerHTML;
	var date_out = els["_date_out"].value;
	var date_in = els["_date_in"].value;
	var done = els["_done"].checked?1:0;
	var designer_note = els["_designer_note"].value;
	var napomena = trim(els["_napomena"].value);
	
	var act_data = "id={!!}";
	act_data += "editor="+urednik_id+"{!!}";
	act_data += "designer="+dizajner_id+"{!!}";
	act_data += "done="+done+"{!!}";
	act_data += "date_out="+date_out+"{!!}";
	act_data += "date_in="+date_in+"{!!}";
	act_data += "designer_note="+escape(designer_note)+"{!!}";
	act_data += "napomena="+escape(napomena);
	
	var li = document.createElement("li");
	if(done){
		li.style.border = "2px solid darkgreen";
	}
	var html = '<input type="hidden" name="act_data_'+newID+'" value="'+act_data+'" />';
	html += '<input type="button" onclick="removeFromParent(this.parentNode)" class="delete" />';
	html += '<input type="button" title="delete" onclick="ugovorEditAction(this)" class="edit" />';
	if(napomena.length){
		imanap = '<img src="gui/icons/napomena.gif" align="right" napomena="'+napomena+'" onclick="alert(this.getAttribute(\'napomena\'))" />';
	}else{
		imanap = '';
	}
	html += '<span class="act_editor">'+imanap+urednik_name+'</span>';
	html += '<span class="act_date">'+date_out+' - '+date_in+'</span>';
	html += '<span class="act_designer_note"><pre>'+designer_note+'</pre></span>';
	html += '<span class="act_designer">'+dizajner_name+'</span>';
	
	li.innerHTML = html;
	if(edit){
		destObj.parentNode.insertBefore(li,destObj);
		destObj.parentNode.removeChild(destObj);
	}else{
		destObj.insertBefore(li,destObj.childNodes[0]);
	}
	closeYpAjaxForm();
}
function addInternetDataPeriodi(btn){
	var ul = btn.parentNode.parentNode.getElementsByTagName("ul")[0];
	var lis = ul.getElementsByTagName("li");
	var l = lis.length;
	
	var nli = lis[l-1].cloneNode(true);
	var els = Array("input","label");
	var index;
	
	for(var i=0; i<els.length; i++){
		var _els = nli.getElementsByTagName(els[i]);
		for(var j=0; j<_els.length; j++){
			if(_els[j].nodeName.toLowerCase() == "label"){
				var f = _els[j].getAttribute("for");
				index = parseInt(f.substr(f.lastIndexOf("_")+1))+1;
				_els[j].setAttribute("for",f.substr(0,f.lastIndexOf("_")+1)+index);
			}else{
				if(_els[j].name){
					var n = _els[j].name;
					index = parseInt(n.substr(n.lastIndexOf("_")+1))+1;
					_els[j].name = n.substr(0,n.lastIndexOf("_")+1)+index;
					_els[j].id = _els[j].name;
				}
			}
		}
	}
	ul.appendChild(nli);
}
function removeInternetDataPeriodi(li){
	var l = parseInt(li.parentNode.getElementsByTagName("li").length);
	if(l>1){
		li.parentNode.removeChild(li);
	}
}
function ugovorMakePlan(btn){
	var brrata = document.getElementById("plan_br_rata");
	brrata.value = brrata.value.replace(/[^\d]/g,"");
	brrata.value = trim(brrata.value).length>0?parseInt(trim(brrata.value)):1;
	
	var d = document.getElementById("plan_avans_date");
	var bruto = document.getElementById("ugovor_iznos_bruto").value;
	var korekcija = document.getElementById("ugovor_iznos_korekcija").value;
	var porez = document.getElementById("ugovor_iznos_porez").value;
	var neto = document.getElementById("ugovor_iznos_neto").value;
	var avans = document.getElementById("plan_avans").value;
	var np = document.getElementById("plan_np").value;
	
	
	
	date = trim(d.value);
	if(!date.length || !date.match(/^\d{1,2}\.\d{1,2}\.\d{2,4}$/)){
		//alert("Morate uneti validan datum plana otplate! (dd.mm.gggg)");
		//d.focus();
		//d.select();
		return;
	}
	
	var action = "a=plan&mod=makeTable";
	action += "&date="+date;
	action += "&brrata="+brrata.value;
	action += "&bruto="+bruto;
	action += "&korekcija="+korekcija;
	action += "&porez="+porez;
	action += "&neto="+neto;
	action += "&avans="+avans;
	action += "&np="+np;
	
	LoadRSDoc("ugovori.php?"+action,"afterUgovorMakePlan");
}
function afterUgovorMakePlan(response){
	var hldr = document.getElementById("plan_table_holder");
	hldr.innerHTML = response;
}
function onChangePlanOtplate(inpt){
	var tr = inpt.parentNode.parentNode;
	var td = tr.getElementsByTagName("td");
	
	// obracun neto i porez
		var por = document.getElementById("ugovor_porez");
		var nto = td[1].getElementsByTagName("input")[0];
		var ppor = td[3].getElementsByTagName("input")[0];
		
		var val = parseFloat(trim(inpt.value));
		var p = parseFloat(por.options[por.selectedIndex].getAttribute("perc"));
		p = parseFloat(val*p/(100+p));
		ppor.value = number_format(p,2);
		nto.value = number_format(val-p,2);
		inpt.value = number_format(val,2);
		
	// obracun ukupno
		var summary = document.getElementById("summary");
		var tbl = tr.parentNode; trs = tbl.getElementsByTagName("tr");
		var u_bruto=u_neto=u_porez=0;
		for(i=1; i<trs.length; i++){
			var tds = trs[i].getElementsByTagName("td");
			if(tds[0].getElementsByTagName("input").length>0){
			//if(1){
				var _nto = tds[1].getElementsByTagName("input")[0]; _nto = strip_number_format(_nto.value);
				var _bto = tds[2].getElementsByTagName("input")[0]; _bto = strip_number_format(_bto.value);
				var _por = tds[3].getElementsByTagName("input")[0]; _por = strip_number_format(_por.value);
				u_neto += parseFloat(_nto);
				u_bruto += parseFloat(_bto);
				u_porez += parseFloat(_por);
			}
		}
		var divs = summary.getElementsByTagName("div");
		divs[3].innerHTML = number_format(u_neto,2);
		divs[2].innerHTML = number_format(u_bruto,2);
		divs[4].innerHTML = number_format(u_porez,2);
		//alert(u_neto+"\n"+u_bruto+"\n"+u_porez);
}
function ugovorAddOtplata(){
	var ul = document.getElementById("otplataList");
	var lis = ul.getElementsByTagName("li");
	var tpl = lis[0];
	var li = tpl.cloneNode(true);
	var lastID = parseInt(lis[lis.length-2].id);
	lastID = lastID>0?lastID:0;
	li.id=lastID+1;
	var inpt = li.getElementsByTagName("input");
	inpt[1].name = "datum"+li.id;
	inpt[1].id = inpt[1].name;
	ul.insertBefore(li,lis[lis.length-1]);
}
function ugovorRemoveOtplata(){
	var ul = document.getElementById("otplataList");
	var li = ul.getElementsByTagName("li");
	for(var i=0; i<li.length; i++){
		if(li[i].className=="selected"){
			ul.removeChild(li[i]);
			i--;
		}
	}
}
function  updateUgovorOtplataNtoPorez(inpt){
	var inpts = inpt.parentNode.parentNode.getElementsByTagName("input");
	var val = parseFloat(strip_number_format(inpt.value));
	var porezobj = document.getElementById("ugovor_porez");
	var perc = parseFloat(porezobj.options[porezobj.selectedIndex].getAttribute("perc"));
	
	var tmp = (100+perc)/100;
	var neto = val/tmp;
	var porez = val-neto;
	
	
	inpts[4].value = number_format(porez,2,",",".");
	inpts[3].value = number_format(neto,2,",",".");
	
}
function ugovorSelectKomitentZR(){
	var zr = document.getElementById("ugovor_komitent_zr");
	var banka = document.getElementById("ugovor_komitent_banka");
	var komitent = document.getElementById("ugovor_komitent_id");
	if(komitent.value>0){
		LoadRSDoc("ugovori.php?a=ugovorKomitentZR&kom="+komitent.value+"&zr="+escape(zr.value)+"&banka="+banka.value,"ypAjaxForm");
	}else{
			alert("Prvo odaberite komitenta!");
	}
}
function addUgovorKomitentZR(forma){
	var sZR = forma.elements["zr"];
	var zrOBJ = document.getElementById("ugovor_komitent_zr");
	var bankaOBJ = document.getElementById("ugovor_komitent_banka");
	var zr;
	var banka;
	if(sZR.value !== "-1"){
		var tmp = sZR.value.split("{!}",2);
		zr = tmp[0];
		banka = tmp[1];
	}else{
		zr=forma.elements["new_zr"].value;
		banka=forma.elements["new_banka"].value;
	}
	zrOBJ.value = zr;
	bankaOBJ.value=banka;
	closeYpAjaxForm();
}
function UgovorAddLink(btn){
	var ul = btn.parentNode.nextSibling.nextSibling;
	var li = ul.getElementsByTagName("li");
	if(li.length<4){
		var nli = li[li.length-1].cloneNode(true);
		nli.id = "";
		var s = nli.getElementsByTagName("select")[0];
		var lastpos = s.name.lastIndexOf("_");
		var base = s.name.substr(0,lastpos)
		var index = parseInt(s.name.substr(lastpos+1));
		s.name = base+"_"+(index+1); s.id = s.name;
		
		ul.appendChild(nli);
	}
}

function afterCheckLogo(response,id){
	var tmp = response.split("{!}",2);
	var code = parseInt(tmp[0]);
	var msg = tmp[1];
	var obj = document.getElementById(id);
	if(obj){
		if(code){
			obj.style.background = "#f00";
			obj.style.color = "#fff";
			obj.title = msg;
		}else{
			obj.style.background = "";
			obj.style.color = "";
			obj.title = "";
		}
	}
}

function afterDeleteUgovor(response){
	var tmp = response.split("{!}",2);
	var code = parseInt(tmp[0]);
	var msg = tmp[1];
	alert(msg);
	if(!code){
		LoadRSDoc("ugovori.php?a=pregled",'setContent');
	}
}